package com.ease.map.handler.feature.draw {
    import com.ease.map.Map;
    import com.ease.map.common.enum.LayerTypeEnum;
    import com.ease.map.common.enum.MapActionEnum;
    import com.ease.map.common.util.GMath;
    import com.ease.map.cursor.CrossCursor;
    import com.ease.map.cursor.MoveFeatureCursor;
    import com.ease.map.events.EditEvent;
    import com.ease.map.events.MapEvent;
    import com.ease.map.geometry.PointGeometry;
    import com.ease.map.geometry.PolylineGeometry;
    import com.ease.map.geometry.basetype.Location;
    import com.ease.map.geometry.basetype.Pixel;
    import com.ease.map.handler.feature.draw.AbstractEditHandler;
    import com.ease.map.handler.feature.draw.snap.SnapReturn;
    import com.ease.map.handler.feature.draw.snap.SnapTypeEnum;
    import com.ease.map.layer.FeatureLayer;
    
    import flash.events.KeyboardEvent;
    import flash.events.MouseEvent;
    import flash.ui.Keyboard;
    
    import mx.collections.ArrayCollection;
    import mx.managers.CursorManager;

    /**
     *1、修改线节点位置。 点击要移动的节点，此时被编辑的锚点高亮，编辑过程中可以拖动地图，双击结束编辑。
     *2、移动设施。鼠标按住CTRL键，鼠标移动到设施上， 变为手型。鼠标down开始移动，鼠标up移动结束
     *3、删除设施
     * */
    [ExcludeClass]
    public class EditLineHandler extends AbstractEditHandler {
        /**
         *标识是否在新增拐点过程中，这个过程包括mousedown mouseup。
         * 以此控制，是新增节点的步骤，还是拖动节点的步骤
         * */
        private var addVertexProcessflag:Boolean = false;

        public function EditLineHandler(map:Map, handlername:String) {
            super(map, handlername);
        }

        override protected function registerListeners():void {
//            this.blackBoard.setInfo("线编辑，默认编辑节点模式  \n单击线---增加节点   \n高亮节点---Delete删除节点   \n单击节点---移动节点 \n ctrl键---进入移动模式 \n ESC键---退出移动模式");
            if (this._drawContainer == null) {
                this._drawContainer = new FeatureLayer(-1, "graphic");
                this._drawContainer.layerType = LayerTypeEnum.DYNAMICLAYER;
                this.map.addLayer(_drawContainer, true);
            }
            map.operateMode = MapActionEnum.MAP_EDIT;
            this._clickHandler.active = true;
            this._clickHandler.doubleClick = this.mouseDblClick;
            if (this.map) {
                this.editFeature.addEventListener(MouseEvent.MOUSE_OVER, mouseOver);
                this.editFeature.addEventListener(MouseEvent.MOUSE_OUT, mouseOut);
                this.map.addEventListener(EditEvent.VERTEX_MOUSE_OVER, vertexMouseOver);
                this.map.addEventListener(EditEvent.VERTEX_MOUSE_OUT, vertexMouseOut);
                this.map.addEventListener(EditEvent.ANCHORPOINT_DOWN, anchorDown);
                this.map.addEventListener(EditEvent.ANCHORPOINT_UP, anchorUp);
                this.map.stage.addEventListener(KeyboardEvent.KEY_DOWN, keyboardDown);
                this.map.addEventListener(MouseEvent.MOUSE_DOWN, mouseDown);
                this.map.addEventListener(MapEvent.MOVE_END, this.updateZoom);
                this.map.addEventListener(MouseEvent.MOUSE_MOVE, mouseMove);
				this.map.stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);

            }
        }

        override protected function unregisterListeners():void {

            this._drawContainer.clear();
            this.map.removeLayer(this._drawContainer);
            this._drawContainer = null;
            this._clickHandler.active = false;
            if (this.map) {
                this.map.removeEventListener(EditEvent.VERTEX_MOUSE_OVER, vertexMouseOver);
                this.map.removeEventListener(EditEvent.VERTEX_MOUSE_OUT, vertexMouseOut);
                this.map.removeEventListener(EditEvent.ANCHORPOINT_UP, anchorUp);
                this.map.removeEventListener(EditEvent.ANCHORPOINT_DOWN, anchorDown);
                this.editFeature.removeEventListener(MouseEvent.MOUSE_OUT, mouseOut);
                this.map.stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyboardDown);
                this.map.removeEventListener(MouseEvent.MOUSE_DOWN, mouseDown);
                this.map.removeEventListener(MapEvent.MOVE_END, this.updateZoom);
                this.map.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMove);
				this.map.stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);

            }
            this.map.operateMode = MapActionEnum.MAP_PAN;
        }

        private function anchorDown(event:EditEvent):void {
            if (DRAG_VERTICES_MODE) {
                var pixel:Pixel = new Pixel(map.mouseX, map.mouseY);
                var lonlat:Location = this.map.getLocationFromLayerPx(pixel);
                pointDown = new PointGeometry(lonlat.x, lonlat.y);
            }


        }

        private function anchorUp(event:EditEvent):void {
            if (DRAG_VERTICES_MODE) {
                var pixel:Pixel = new Pixel(map.mouseX, map.mouseY);
                var lonlat:Location = this.map.getLocationFromLayerPx(pixel);
                pointUp = new PointGeometry(lonlat.x, lonlat.y);
                //第一次按下开始拖动节点
                if (!bIsAnchorMove && bIsFirstAnchor && pointUp.equals(pointDown)) {
                    editAnchor = event.anchorPoint;
                    editAnchor.setEditMode(true);
                    bIsAnchorMove = true;

                    this.map.addEventListener(MouseEvent.MOUSE_UP, mouseUp);

                    CursorManager.removeAllCursors();
                    CursorManager.setCursor(CrossCursor);
                    var line:PolylineGeometry = editAnchor.parentFeature.geometry as PolylineGeometry;
                    var point:PointGeometry;
                    if (editAnchor.pointIndex == 0) {
                        editMode = 0;
                        editingPoint1 = line.pointList.getItemAt(editAnchor.pointIndex + 1) as PointGeometry;
                        _startPoint1 = map.getLayerPxFromLocation(new Location(editingPoint1.x, editingPoint1.y));
                    }
                    else if (editAnchor.pointIndex == line.pointList.length - 1) {
                        editMode = 0;
                        editingPoint1 = line.pointList.getItemAt(editAnchor.pointIndex - 1) as PointGeometry;
                        _startPoint1 = map.getLayerPxFromLocation(new Location(editingPoint1.x, editingPoint1.y));
                    }
                    else {
                        editMode = 1;
                        editingPoint1 = line.pointList.getItemAt(editAnchor.pointIndex - 1) as PointGeometry;
                        _startPoint1 = map.getLayerPxFromLocation(new Location(editingPoint1.x, editingPoint1.y));
                        editingPoint2 = line.pointList.getItemAt(editAnchor.pointIndex + 1) as PointGeometry;
                        _startPoint2 = map.getLayerPxFromLocation(new Location(editingPoint2.x, editingPoint2.y));

                    }
                }

            }
            //如果删除节点模式打开，鼠标点击锚点，删除此节点
            if (DELETE_VERTICES_MODE) {
                deleteVertex();
            }
        }

        private function mouseDown(event:MouseEvent):void {
            isMouseDowning = false;
            var pixel:Pixel = new Pixel(map.mouseX, map.mouseY);
            var lonlat:Location = this.map.getLocationFromLayerPx(pixel);
            pointDown = new PointGeometry(lonlat.x, lonlat.y);

            //默认下的增加节点状态
            if (!MOVE_MODE && editMode == 100 && createPoint != null) {
                addVertexProcessflag = true;
                //判断此点在线的index
                var pointList:ArrayCollection = (editFeature.geometry as PolylineGeometry).pointList;
                for (var i:int = 0; i < pointList.length - 1; i++) {
                    //如果点在此条线段上，退出
                    if (GMath.isPointInLine(createPoint, pointList.getItemAt(i) as PointGeometry, pointList.getItemAt(i + 1) as PointGeometry)) {
                        pointList.addItemAt(createPoint, i + 1);
                        break;
                    }
                }
                createPoint = null;
                editFeature.editing = true;
                editFeature.executeDrawing();
            }

        }

        private function mouseUp(event:MouseEvent):void {
            isMouseDowning = true;
            var pixel:Pixel = new Pixel(map.mouseX, map.mouseY);
            var lonlat:Location = this.map.getLocationFromLayerPx(pixel);
            pointUp = new PointGeometry(lonlat.x, lonlat.y);

            if (!pointUp.equals(pointDown)) {
            }
            else {
                //移动中再按下鼠标，结束移动
                if (MOVE_MODE && isFeatureMoving) {
                    _drawContainer.graphics.clear();
                    CursorManager.removeAllCursors();
                    editFeature.executeDrawing();
                    MOVE_MODE = false;
                    isFeatureMoving = false;
                    editMode = 100;
                    this.map.removeEventListener(MouseEvent.MOUSE_UP, mouseUp);
                }
                //第一次移动 按下
                else if (MOVE_MODE && !isFeatureMoving) {
                    isFeatureMoving = true;
                    moveStartPiexl = new Pixel(_drawContainer.mouseX, _drawContainer.mouseY);
                    moveStartPoint = this.map.getLocationFromLayerPx(moveStartPiexl);
                }
                //编辑线
                if (bIsAnchorMove && !bIsFirstAnchor) {
                    //判断是否捕捉到了节点
                    if (snapReturn != null && snapReturn.snapPoint != null) {
                        editAnchor.geoPoint.x = snapReturn.snapPoint.x;
                        editAnchor.geoPoint.y = snapReturn.snapPoint.y;
                        if (this.snapClickCallback != null) {
//                            this.snapClickCallback(snapReturn.snapFeature, editAnchor.geoPoint);
							this.snapClickCallback(snapReturn.snapFeatures, editAnchor.geoPoint);
                        	map.clearHighLight();
						}
                        snapReturn = null;
                    }
                    else {
                        var piexl:Pixel = new Pixel(this._drawContainer.mouseX, this._drawContainer.mouseY);
                        editAnchor.geoPoint.x = this.map.getLocationFromLayerPx(piexl).lon;
                        editAnchor.geoPoint.y = this.map.getLocationFromLayerPx(piexl).lat;
                    }

                    _drawContainer.graphics.clear();
                    editAnchor.setEditMode(false);
                    bIsAnchorMove = false;
                    CursorManager.removeAllCursors();
                    editMode = 100;
                    editAnchor.parentFeature.executeDrawing();
                    bIsFirstAnchor = true;

                }
            }

        }
		
        private function mouseOver(event:MouseEvent):void {
            if (MOVE_MODE) {
                //设施移动模式打开
                _drawContainer.graphics.clear();
                CursorManager.removeAllCursors();
                CursorManager.setCursor(MoveFeatureCursor);
                this.map.addEventListener(MouseEvent.MOUSE_UP, mouseUp);
            }
            else if (!bIsAnchorMove) {
                CursorManager.removeAllCursors();
            }

        }

        private function mouseOut(event:MouseEvent):void {
            if (MOVE_MODE && !isFeatureMoving) {
                CursorManager.removeAllCursors();
            }
        }

        private function mouseMove(event:MouseEvent):void {
            //移动设施
            if (MOVE_MODE && isFeatureMoving && isMouseDowning) {
                //清除已经画的临时增加点
                _drawContainer.graphics.clear();
                moveEndPiexl = new Pixel(this._drawContainer.mouseX, this._drawContainer.mouseY);
                moveEndPoint = this.map.getLocationFromLayerPx(moveEndPiexl);
                var offsetLocation:Location = new Location(moveEndPoint.x - moveStartPoint.x, moveEndPoint.y - moveStartPoint.y);

                editFeature.geometry.offset(offsetLocation);
                editFeature.executeDrawing();
                moveStartPiexl = new Pixel(this._drawContainer.mouseX, this._drawContainer.mouseY);
                moveStartPoint = this.map.getLocationFromLayerPx(moveStartPiexl);
            }
            else {
                if (!MOVE_MODE) {
                    //编辑设施
                    if (editMode == 100 && ADD_VERTICES_MODE) {
                        createPointUndertheMouse(event);
                    }
                    else if (editMode != 100 && DRAG_VERTICES_MODE) {
                        bIsFirstAnchor = false;
                        //捕捉设施打开				
                        super.mouseMoveSnapHandler(event);

                        if (editMode == 0) {
                            _drawContainer.graphics.clear();
                            _drawContainer.graphics.lineStyle(2, 0x0000FF);
                            _drawContainer.graphics.moveTo(_drawContainer.mouseX, _drawContainer.mouseY);
                            _drawContainer.graphics.lineTo(_startPoint1.x, _startPoint1.y);
                            _drawContainer.graphics.endFill();
                        }
                        if (editMode == 1) {
                            _drawContainer.graphics.clear();
                            _drawContainer.graphics.lineStyle(2, 0x0000FF);
                            _drawContainer.graphics.moveTo(_drawContainer.mouseX, _drawContainer.mouseY);
                            _drawContainer.graphics.lineTo(_startPoint1.x, _startPoint1.y);
                            _drawContainer.graphics.moveTo(_drawContainer.mouseX, _drawContainer.mouseY);
                            _drawContainer.graphics.lineTo(_startPoint2.x, _startPoint2.y);
                            _drawContainer.graphics.endFill();

                        }
                    }
                }
            }
        }

        //鼠标移动时，捕获离鼠标最近点，显示出增加节点状态
        private function createPointUndertheMouse(event:MouseEvent):void {

            var pixel:Pixel = new Pixel(this._drawContainer.mouseX, this._drawContainer.mouseY);
            var lonlat:Location = this.map.getLocationFromLayerPx(pixel);
            var mousePoint:PointGeometry = new PointGeometry(lonlat.x, lonlat.y);
            var distance:Number = map.resolution * snapTolerance;
            var snapPoint:PointGeometry = new PointGeometry;

            editFeature.buttonMode = false;
            snapReturn = new SnapReturn();
            snapReturn.snapType = editFeature.geometry.getTolerancePoint(mousePoint, distance, snapPoint);
            //增加节点
            if (snapReturn.snapType == SnapTypeEnum.SNAP_INLINE) {
                createPoint = new PointGeometry(snapPoint.x, snapPoint.y);
                //画出动态捕捉的点
                _drawContainer.graphics.clear();
                _drawContainer.graphics.beginFill(0x999999, 0.6);
                _drawContainer.graphics.lineStyle(1, 0x000000);
                _drawContainer.graphics.drawRect(_drawContainer.mouseX - 5, _drawContainer.mouseY - 5, 10, 10);
            }
            else {
                createPoint = null;
                _drawContainer.graphics.clear();
            }
        }

        private function updateZoom(evt:MapEvent):void {

            if (evt.zoomChanged) {
                if (editMode == 0 && DRAG_VERTICES_MODE) {
                    _startPoint1 = map.getLayerPxFromLocation(new Location(editingPoint1.x, editingPoint1.y));
                    _drawContainer.graphics.clear();
                    _drawContainer.graphics.lineStyle(2, 0x0000FF);
                    _drawContainer.graphics.moveTo(_drawContainer.mouseX, _drawContainer.mouseY);
                    _drawContainer.graphics.lineTo(_startPoint1.x, _startPoint1.y);
                    _drawContainer.graphics.endFill();
                }
                if (editMode == 1 && DRAG_VERTICES_MODE) {
                    _startPoint1 = map.getLayerPxFromLocation(new Location(editingPoint1.x, editingPoint1.y));
                    _startPoint2 = map.getLayerPxFromLocation(new Location(editingPoint2.x, editingPoint2.y));
                    _drawContainer.graphics.clear();
                    _drawContainer.graphics.lineStyle(2, 0x0000FF);
                    _drawContainer.graphics.moveTo(_drawContainer.mouseX, _drawContainer.mouseY);
                    _drawContainer.graphics.lineTo(_startPoint1.x, _startPoint1.y);
                    _drawContainer.graphics.moveTo(_drawContainer.mouseX, _drawContainer.mouseY);
                    _drawContainer.graphics.lineTo(_startPoint2.x, _startPoint2.y);
                    _drawContainer.graphics.endFill();

                }
            }
        }

    }
}